package com.woniuxy.gobang84.ui;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.woniuxy.gobang84.entity.Message;
import com.woniuxy.gobang84.util.Global;

import javafx.application.Platform;

/**
 * 接收客户端信息的线程
 *
 * @author 老谭 (<a href="http://www.woniuxy.com">蜗牛学苑</a>)
 *
 */
public class ServerThread extends Thread {
	private NetGameStage netGameStage;

	public ServerThread(NetGameStage netGameStage) {
		this.netGameStage = netGameStage;
	}

	@Override
	public void run() {
		try {
			ServerSocket serverSocket = new ServerSocket(Global.myPort);
			while (true) {
				Socket socket = serverSocket.accept(); // 阻塞，等待客户端发送请求
				InputStream is = socket.getInputStream();
				// 处理落子信息
				ObjectInputStream ois = new ObjectInputStream(is);
				try {
					Message message = (Message) ois.readObject();
					// JaavFX规定，不能再非FX的线程中更新界面
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							netGameStage.updateUI(message);
						}
					});

				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
